package org.amphiprion.diceroller.dao;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.amphiprion.diceroller.ApplicationConstants;
import org.amphiprion.diceroller.entity.DiceDefinition;
import org.amphiprion.diceroller.entity.DiceFaceDefinition;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.util.Log;

public class DiceDefinitionDao extends AbstractXmlDao {
	private static DiceDefinitionDao instance;

	public static DiceDefinitionDao getInstance() {
		if (instance == null) {
			instance = new DiceDefinitionDao();
		}
		return instance;
	}

	public DiceDefinition getDiceDefinition(String type) {
		InputStream is = null;
		try {
			DiceDefinition definition = new DiceDefinition();
			definition.setId(type);

			File f = new File(ApplicationConstants.MESH_DIRECTORY + "/" + type + "-numberNormalLink.xml");

			if (f.exists()) {
				is = new FileInputStream(f);
			}
			if (is == null) {
				throw new RuntimeException("File " + f.getAbsolutePath() + " does not exist!");
			}

			DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
			builderFactory.setNamespaceAware(true);

			DocumentBuilder builder = builderFactory.newDocumentBuilder();
			Document document = builder.parse(is);

			NodeList list = document.getElementsByTagName("dice");
			Element diceNode = (Element) list.item(0);
			String sNormal = getAttribute(diceNode, "normalForResult", "0,0,1");
			String[] sNormals = sNormal.split(",");
			float[] normal = new float[3];
			normal[0] = Float.parseFloat(sNormals[0]);
			normal[1] = Float.parseFloat(sNormals[1]);
			normal[2] = Float.parseFloat(sNormals[2]);
			definition.setNormalForResult(normal);

			list = document.getElementsByTagName("face");
			for (int i = 0; i < list.getLength(); i++) {
				Element faceNode = (Element) list.item(i);
				String number = getAttribute(faceNode, "number", "");
				sNormal = getAttribute(faceNode, "normal", "0,0,1");
				sNormals = sNormal.split(",");
				normal = new float[3];
				normal[0] = Float.parseFloat(sNormals[0]);
				normal[1] = Float.parseFloat(sNormals[1]);
				normal[2] = Float.parseFloat(sNormals[2]);

				DiceFaceDefinition defFace = new DiceFaceDefinition();
				defFace.setNumber(number);
				defFace.setNormal(normal);
				definition.getFaceDefinitions().add(defFace);
				// Log.d(ApplicationConstants.PACKAGE, type + " - face " + number + " - normal:" + sNormal);
			}
			is.close();

			return definition;
		} catch (Throwable e) {
			Log.e(ApplicationConstants.PACKAGE, "", e);
			if (is != null) {
				try {
					is.close();
				} catch (Throwable ex) {
				}
			}
			return null;
		}
	}

}
